package com.hxd.mall.network.base

import com.hexin.locallibrary.network.OkHttpManager
import com.hxd.mall.R
import com.hxd.mall.base.IBaseView
import com.hxd.mall.constant.HxdConstants.Alias
import com.hxd.mall.constant.HxdConstants.isSaveAlias
import com.hxd.mall.constant.HxdConstantsAccount
import com.hxd.mall.constant.HxdConstantsAccount.token
import com.hxd.mall.constant.HxdGlobalInfo
import com.hxd.mall.constant.HxdGlobalInfo.instance
import com.hxd.mall.utils.local.HxdSharePreferenceUtil
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getBooleanData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getStringData
import com.hxd.mall.utils.local.ThirdInitUtil
import com.hxd.mall.utils.local.ThirdInitUtil.bindJPush
import com.hxd.mall.utils.open.DeviceInfoUtil
import com.hxd.mall.utils.open.NetTypeUtils.getNetWorkType
import com.hxd.mall.utils.open.NetUtil
import com.hxd.mall.utils.open.NetUtil.getNetworkType
import com.hxd.mall.utils.open.ToastUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * 网路请求base封装
 * 注意：
 *   1. 如果网络不通，自动弹出toast
 *   2. 网络支持自动弹出隐藏Loading
 */
object BaseRequest {

    /**
     * 无请求Loading
     */
    fun <T> request(
        observer: Observable<T>,
        onHandleSuccessCustom: (T) -> Unit,
        onHandleErrorCustom: (BaseBean) -> Unit
    ) {
//        if (!NetUtil.isNetworkAvailable(HxdGlobalInfo.instance)) {
//            ToastUtil.showToast(HxdGlobalInfo.instance.getString(R.string.net_error_tip))
//            return
//        }

        requestCommit(observer, null, onHandleSuccessCustom, onHandleErrorCustom)
    }

    /**
     * 无请求Loading,需要关闭下拉刷新
     */
    fun <T> requestFinishRefresh(
        observer: Observable<T>,
        baseView: IBaseView,
        onHandleSuccessCustom: (T) -> Unit,
        onHandleErrorCustom: (BaseBean) -> Unit
    ) {
//        if (!NetUtil.isNetworkAvailable(HxdGlobalInfo.instance)) {
//            ToastUtil.showToast(HxdGlobalInfo.instance.getString(R.string.net_error_tip))
//            baseView.finishRefresh()
//            return
//        }

        requestCommit(observer, baseView, onHandleSuccessCustom, onHandleErrorCustom)
    }

    /**
     * 需要弹出Dialog
     */
    fun <T> request(
        observer: Observable<T>,
        baseView: IBaseView,
        onHandleSuccessCustom: (T) -> Unit,
        onHandleErrorCustom: (BaseBean) -> Unit
    ) {
//        if (!NetUtil.isNetworkAvailable(HxdGlobalInfo.instance)) {
//            baseView.hideLoading()
//            ToastUtil.showToast(HxdGlobalInfo.instance.getString(R.string.net_error_tip))
//            baseView.finishRefresh()
//            return
//        }

        baseView.showLoading()
        requestCommit(observer, baseView, onHandleSuccessCustom, onHandleErrorCustom)
    }

    /**
     * 需要弹出Dialog,不关闭Dialog
     */
    fun <T> requestJustShowDailog(
        observer: Observable<T>,
        baseView: IBaseView,
        onHandleSuccessCustom: (T) -> Unit,
        onHandleErrorCustom: (BaseBean) -> Unit
    ) {
//        if (!NetUtil.isNetworkAvailable(HxdGlobalInfo.instance)) {
//            baseView.hideLoading()
//            ToastUtil.showToast(HxdGlobalInfo.instance.getString(R.string.net_error_tip))
//            baseView.finishRefresh()
//            return
//        }
        baseView.showLoading()
        requestCommit(observer, baseView, onHandleSuccessCustom, onHandleErrorCustom, false)
    }


    /**
     * 需要弹出Dialog,一直显示Dialog
     */
    fun <T> requestAlwayShowDailog(
        observer: Observable<T>,
        baseView: IBaseView,
        onHandleSuccessCustom: (T) -> Unit,
        onHandleErrorCustom: (BaseBean) -> Unit
    ) {
//        if (!NetUtil.isNetworkAvailable(HxdGlobalInfo.instance)) {
//            baseView.hideLoading()
//            ToastUtil.showToast(HxdGlobalInfo.instance.getString(R.string.net_error_tip))
//            baseView.finishRefresh()
//            return
//        }
        baseView.showLoading()
        requestCommit(observer, baseView, onHandleSuccessCustom, onHandleErrorCustom, false, true)
    }

    /**
     * 网络请求提交
     */
    private fun <T> requestCommit(
        observer: Observable<T>,
        baseView: IBaseView?,
        onHandleSuccessCustom: (T) -> Unit,
        onHandleErrorCustom: (BaseBean) -> Unit,
        closeDialog: Boolean = true,
        isAlwayDialog: Boolean = false
    ) {
        if (!NetUtil.isNetworkAvailable(HxdGlobalInfo.instance)) {
            ToastUtil.showToast(HxdGlobalInfo.instance.getString(R.string.net_error_tip))
            baseView?.hideLoading()
            baseView?.finishRefresh()
            return
        }

        //构造请求头参数
        if (OkHttpManager.headerMap.isEmpty()) {
            OkHttpManager.headerMap.apply {
                put("Accept", "application/json")
                put("Content-Type", "application/json")
                put("os", "Android")
                put("accessToken", token ?: "")
                put("channel", HxdConstantsAccount.Channel_Number)
                put("version", HxdGlobalInfo.versionCode)
                put("appId", HxdGlobalInfo.instance.packageName)
                put("systemVersion", DeviceInfoUtil.getSystemVersion())
                put("deviceNum", HxdGlobalInfo.deviceUUID)
                //设备分辨率
                put("screenSize", "${HxdGlobalInfo.deviceHeight}*${HxdGlobalInfo.deviceWidth}")
                put("timestamp", System.currentTimeMillis().toString())
                //设备型号
//                put("deviceVersion", MobileInfoManager.getSystemModel())


//                put("mobileModel", DeviceInfoUtil.getDeviceBrand() + " " + DeviceInfoUtil.getSystemModel())
            }
        } else {
            //登陆后将用户信息中的token更新到header中
            OkHttpManager.headerMap.apply {
                put("accessToken", token ?: "")
            }
        }
        OkHttpManager.headerMap["netType"] = getNetWorkType(instance)

        val value = object : BaseObserver<T>() {
            override fun onHandleSuccess(t: T) {
                onHandleSuccessCustom(t)
                if (closeDialog) {
                    baseView?.hideLoading()
                }
                baseView?.finishRefresh()

                //每次网络请求成功后，极光别名如果绑定失败则重试
                if (!getBooleanData(isSaveAlias, false)) {
                    bindJPush(getStringData(Alias, "") ?: "")
                }
            }

            override fun onHandleError(errorEntity: BaseBean) {
                if (!isAlwayDialog)
                    baseView?.hideLoading()
                baseView?.finishRefresh()
                onHandleErrorCustom(errorEntity)
            }
        }

        observer.compose { observable ->
            observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        }.subscribe(value)

    }

    /**
     * 将map转成json body
     */
//    fun convertToJsonBody(params: HashMap<String, Any>): RequestBody {
//        val json = JSONObject().apply {
//            params.forEach {
//                put(it.key, it.value)
//            }
//        }.toString()
//
//        return RequestBody
//            .create(
//                MediaType.parse("application/json; charset=utf-8"),
//                if (TextUtils.isEmpty(json)) "" else json
//            )
//    }
}